package amtf

import (
	"encoding/json"
	"fmt"
	"server/global"
	"server/model/common/response"
	"server/model/system"
	"server/utils"
	"strings"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func 删除非法id(data any) any {
	switch v := data.(type) {
	case []any:
		for i := range v {
			v[i] = 删除非法id(v[i])
		}
		return v
	case map[string]any:
		for key, value := range v {
			if key == "id" {
				if num, ok := value.(float64); ok && num < 0 {
					delete(v, key)
				}
			} else {
				// 先检查是不是 map 或者 切片，如果是才递归调用
				if _, isMap := value.(map[string]any); isMap {
					v[key] = 删除非法id(value)
				} else if _, isSlice := value.([]any); isSlice {
					v[key] = 删除非法id(value)
				}
			}
		}
		return v
	default:
		return data
	}
}

func A予Auser(c *gin.Context) system.SysUser {
	userID := utils.GetUserID(c)
	Auser = A取user(userID)
	return Auser
}

func A观body(c *gin.Context, 组件 *S组件) (data any, bytes []byte) {
	// userID := utils.GetUserID(c)
	// Auser = A取user(userID)
	A予Auser(c)
	decoder := json.NewDecoder(c.Request.Body)
	err := decoder.Decode(&data)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	data = 删除非法id(data)

	bytes, err = json.Marshal(data)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	组件.A源reqdata = data
	return
}

func 是查设置否(c *gin.Context) (是否 bool) {
	是否 = strings.Contains(c.FullPath(), "/shezhi")
	return
}

func 仅自己观(c *gin.Context, req *S列表req) (err error) {
	if req.A仅自己 {
		id, err := utils.A取用户id(c)
		req.A用户id = fmt.Sprintf("%d", id)
		return err
	}
	return
}

func 记录id否(c *gin.Context, model any) bool {
	if !A有字段否(model, "A用户id") {
		return false
	}
	// A取字段反射值(model, "A用户id")
	userID := utils.GetUserID(c)
	A予字段值(model, "A用户id", userID)
	return true
}

//	func 记录CreatedBy用户(c *gin.Context, model any) {
//		记录用户到字段(c, model, "CreatedBy")
//	}

func 查询正常否(c *gin.Context, err error) bool {
	message := "查询出错"
	return 正常否(c, err, message)
}

func 正常否(c *gin.Context, err error, message string) bool {
	if err != nil {
		global.A_LOG.Error(message, zap.Error(err))
		response.FailWithMessage(message+":"+err.Error(), c)
		return false
	}
	return true
}
